<template>
  <BasicModal
    v-bind="$attrs"
    width="400"
    :title="title"
    :canFullscreen="false"
    :destroyOnClose="true"
    :maskClosable="false"
    @register="registerModal"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from '../Category.data';
import { saveOrUpdate } from '../Category.api';
import { filterObj } from "/@/utils/common/compUtils";

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
//设置标题
const title = ref();
//表单配置
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  console.info("useModalInner@@@", data, isUpdate.value, !!data.record)

  var temp = { }
  var record = { }
  if(isUpdate.value && !!data.record) {
    temp = edit(data.record)
  } else {
    if (!!data.record) {
      temp = addChildren(data.record)
    } else {
      temp = addParent()
      data.record = {}
    }
  }

  Object.assign(record, data.record, temp);

  // 无论新增还是编辑，都可以设置表单值
  // console.info("data.record@@", data.record.cId)
  if (typeof data.record === "object") {
    await setFieldsValue({
      ...record
    });
  }
});

// 添加一级分类
function addParent() {
  title.value = "添加一级分类";
  var temp = {
    id: '',
    parentId : 0,
    level: 0,
    parentTitle : "顶级分类"
  }
  return temp;
}

// 添加子分类
function addChildren(record) {
  title.value = "添加子分类";
  var temp = {
    id: '',
    parentId : record.id,
    level: eval(record.level + "+1"),
    parentTitle : record.name,
    name: ''
  }
  return temp;
}

// 编辑分类
function edit(record) {
  title.value = "编辑";
  var preantId = 0;
  var level = 0
  if (!!record.preantId) {
    preantId = record.preantId;
    level = record.level;
  } 
  var temp = {
    id: record.id,
    parentId : preantId,
    level: level,
    parentTitle : "顶级分类"
  }
  return temp;
}

//表单提交事件
async function handleSubmit() {
  try {
    let values = await validate();
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success', { isUpdate: isUpdate.value, values });
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
</style>